<template>
  <div class="check-password">
    <h2 class="title">密码验证</h2>
    <div class="input-wrapper">
      <van-field
        v-model="password"
        type="password"
        placeholder="请输入密码"
        :error="!!errorMessage"
        :error-message="errorMessage"
      />
    </div>
    <div class="button-wrapper">
      <van-button type="primary" block @click="handleVerify" :loading="loading">
        验证密码
      </van-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useLocationParams } from "@/store/useLocationStore";
import MD5 from "crypto-js/md5";
const { getAllParams, removeParam, updateParam } = useLocationParams();
const router = useRouter();
// const courseId = route.query.courseId as string;
const password = ref("");
const errorMessage = ref("");
const loading = ref(false);

const handleVerify = async () => {
  if (!password.value) {
    errorMessage.value = "请输入密码";
    return;
  }

  try {
    loading.value = true;
    // TODO: Replace with your actual API call
    const response = await verifyPassword(password.value);

    if (response.success) {
      showToast("验证成功");
      removeParam("pd");
      removeParam("oPd");
      removeParam("redirect");
      router.replace({ name: "LiveCourse", query: { ...getAllParams() } });
      // router.push(`/course/detail/${courseId}`);
    } else {
      errorMessage.value = "密码错误";
    }
  } catch (error) {
    showToast("验证失败，请重试");
  } finally {
    loading.value = false;
  }
};

interface VerifyResponse {
  success: boolean;
}

// Mock API function - replace with your actual API call
const verifyPassword = async (password: string): Promise<VerifyResponse> => {
  // Simulate API call
  return new Promise(resolve => {
    setTimeout(() => {
      const md5Password = MD5(password).toString();
      const allParams = getAllParams();
      resolve({ success: md5Password === allParams.pd });
    }, 1000);
  });
};
</script>

<style scoped>
.check-password {
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

.input-wrapper {
  margin-bottom: 20px;
}

.button-wrapper {
  margin-top: 30px;
}
</style>
